import { Env, ResResult } from "#/index";
import axios, { AxiosResponse } from "axios";
import { ErrorCode, getErrorInfo } from "@/utils/const";
import eventEmit from "@/utils//eventEmit";

/**
 * 根据环境返回对应的接口url
 * @param env
 * @returns
 */
export const getApiUrl = (env: Env) => {
  // if (process.env.NODE_ENV) return "";
  return {
    prod: "https://longyi-gis.mmall.com",
    stg: "https://longyi-gis.mklmall.com",
    uat1: "http://longyi-gis.uat1.rs.com",
    dev: "http://longyi-gis.dev.rs.com",
  }[env];
};

/**
 * 配置请求axios
 * @param env
 * @returns
 */
export const https = (env: Env, that) => {
  const https = axios.create();
  https.defaults.timeout = 30000;
  https.defaults.responseType = "json";
  https.defaults.baseURL = getApiUrl(env);
  https.interceptors.request.use(
    (config) => {
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  https.interceptors.response.use(
    (response) => {
      let { data } = response;
      if (data && data.code == 200) {
        return data;
      } else {
        that.loading = false;
        eventEmit.emit("loading", false);
        eventEmit.emit("error", {
          code: ErrorCode.HTTP_ERROR,
          message:
            data.message || data.mgs || getErrorInfo(ErrorCode.HTTP_ERROR),
          data: response,
        });
        throw new Error(
          data.message || data.mgs || getErrorInfo(ErrorCode.HTTP_ERROR)
        );
      }
    },
    (error) => {
      if (error.response) {
        const { statusText } = error.response;
        that.loading = false;
        eventEmit.emit("loading", false);
        eventEmit.emit("error", {
          code: ErrorCode.HTTP_ERROR,
          message: statusText || getErrorInfo(ErrorCode.HTTP_ERROR),
          data: error.response,
        });
        throw new Error(statusText || getErrorInfo(ErrorCode.HTTP_ERROR));
      }
      return Promise.reject(error);
    }
  );
  return https;
};

/**
 * 生成随机数
 * @returns
 */
export const random = () => {
  return parseInt(Math.random() * 1000000000000 + "", 10);
};
